/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.rest.client;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.phase.PhaseInterceptorChain;
import org.apache.cxf.transport.http.AbstractHTTPDestination;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * This is {@link CookiesRepeaterFilter}.
 *
 * @author yisiqi
 * @since 1.0.0
 */
@Slf4j
public class CookiesRepeaterFilter implements ClientRequestFilter {

    @Override
    public void filter(ClientRequestContext context) {
        try {
            HttpServletRequest request = (HttpServletRequest) PhaseInterceptorChain
                    .getCurrentMessage().get(AbstractHTTPDestination.HTTP_REQUEST);

            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                context.getHeaders().add("Cookie", Stream.of(request.getCookies())
                        .map(this::serializingCookie)
                        .collect(Collectors.joining("; ")));
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    private String serializingCookie(Cookie cookie) {
        return String.format("%s=%s", cookie.getName(), cookie.getValue());
    }
}
